package com.cyc.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cyc.common.utils.R;
import com.cyc.gulimall.cart.feign.ProductFeignService;
import com.cyc.gulimall.cart.interceptor.CartInterceptor;
import com.cyc.gulimall.cart.service.CartService;
import com.cyc.gulimall.cart.vo.CartItemVo;
import com.cyc.gulimall.cart.vo.CartVo;
import com.cyc.gulimall.cart.vo.SkuInfoVo;
import com.cyc.gulimall.cart.vo.UserInfoVo;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    private final String CART_PREFIX="gulimall:cart:";

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String)cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)){
            R skuInfo = productFeignService.getSkuInfo(skuId);
            //查询当前商品信息
            SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            //添加商品信息
            CartItemVo cartItem=new CartItemVo();
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(data.getSkuDefaultImg());
            cartItem.setTitle(data.getSkuTitle());
            cartItem.setSkuId(skuId);
            cartItem.setPrice(data.getPrice());

            //sku组合信息
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttrValues(skuSaleAttrValues);

            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));



            return cartItem;
        }else {
            CartItemVo cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));

            return cartItemVo;

        }



    }

    @Override
    public CartVo getCart() {

        CartVo cartVo=new CartVo();
        //区分登陆还是不登录
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        if (userInfoVo.getUserId()!=null){
            //登陆了
            String key = CART_PREFIX + userInfoVo.getUserId();
            //临时购物车合并
            List<CartItemVo> temCartItem = getCartItems(CART_PREFIX + userInfoVo.getUserKey());
            if (temCartItem!=null){
                for (CartItemVo itemVo : temCartItem) {
                    addToCart(itemVo.getSkuId(), itemVo.getCount());
                }
                //清空临时购物车
                clearCart(CART_PREFIX + userInfoVo.getUserKey());
            }

            List<CartItemVo> cartItems = getCartItems(key);

            cartVo.setItems(cartItems);

        }else {
            String key = CART_PREFIX + userInfoVo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(key);
            cartVo.setItems(cartItems);

        }
        return cartVo;
    }

    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    @Override
    public void clearCart(String key) {
        Boolean delete = redisTemplate.delete(key);

    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(),s);

    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.delete(skuId.toString());

    }

    private  BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();

        String cartkey="";
        if (userInfoVo.getUserId()!=null){
            //登陆用户
            cartkey=CART_PREFIX+userInfoVo.getUserId();
        }else{
            cartkey=CART_PREFIX+userInfoVo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartkey);
        return operations;
    }


    private List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        if (values!=null && values.size()>0){
            List<CartItemVo> collect = values.stream().map(item -> {
                CartItemVo vo = JSON.parseObject((String) item, CartItemVo.class);
                return vo;
            }).collect(Collectors.toList());

            return collect;
        }

        return null;
    }


}
